from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.images import ImageSerializer, SKUSerializer
from goods.models import SKUImage, SKU
from meiduo_admin.utils import UserPageNum
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings
from celery_tasks.static_file.tasks import get_detail_html


class ImageView(ModelViewSet):
    # 图片序列化器
    serializer_class = ImageSerializer
    # 图片查询集
    queryset = SKUImage.objects.all()
    # 分页
    pagination_class = UserPageNum

    # permission_classes = [IsAdminUser]

    #  获取sku商品信息
    def simple(self, request):
        #  查询所有的sku商品
        data = SKU.objects.all()
        #  序列化操作返回
        ser = SKUSerializer(data, many=True)
        return Response(ser.data)

    # # 重写拓展类的保存业务逻辑
    # def create(self, request, *args, **kwargs):
    #     # 创建FastDFS连接对象
    #     client = Fdfs_client(settings.FASTDFS_PATH)
    #     # 获取前端传递的image文件
    #     data = request.FILES.get('image')
    #     # 上传图片到fastDFS
    #     res = client.upload_by_buffer(data.read())
    #     # 判断是否上传成功
    #     if res['Status'] != 'Upload successed.':
    #         return Response(status=403)
    #     # 获取上传后的路径
    #     image_url = res['Remote file_id']
    #     # 获取sku_id
    #     sku_id = request.data.get('sku')[0]
    #     # 保存图片
    #     img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
    #
    #     # 生成新的详情页页面
    #     # get_detail_html.delay(img.sku.id)
    #     # 返回结果
    #     return Response(
    #         {
    #             'id': img.id,
    #             'sku': sku_id,
    #             'image': img.image.url  # 这儿返回是完整的路由信息
    #         },
    #         status=201  # 前端需要接受201状态
    #     )
